package com.mspbots.rule.exceptions.ticket;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.cw.request.TenantTicketDTO;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author Dinnes Zhang
 * @date
 */
@Slf4j
@Rule(name = "TicketCompleted", description = "")
public class TicketCompleted extends TicketBaseRule {

    @Override
    @Condition
    public boolean condition(@Fact(FACT) TenantTicketDTO ticket) {
        try {
            if (!ticket.getStatus().toLowerCase().contains("completed")) {
                return false;
            }
            if (!setUserMapping(ticket.getTenantUserId())) {
                return false;
            }
            messages.setBusinessId(ticket.getCwId());
            messages.setBusinessType(BUSINESS_TYPE);
            if (checkMessage(ticket)) {
                return false;
            }
        } catch (Exception e) {
            log.error("TicketCompleted : {}", e.getMessage());
        }
        try {
            Map<String, Object> params = Map.of("tenantId", ticket.getTenantId(), "id", ticket.getCwId());
            JsonNode notes = this.wiseClient.get("/tickets/notes", params).block();
            if (!StringUtils.isEmpty(notes)) {
                return false;
            }
        } catch (Exception e) {
            log.error("Notes : {}", e.getMessage());
            return true;
        }
        return false;
    }

    @Action
    @Async
    @Override
    public void action(@Fact(FACT) TenantTicketDTO tenantTicketDTO) {
        String message = buildMessage(tenantTicketDTO.getCreatedTime());
        Map<String, Object> params = Map.of("TicketLink", suffixTicketLink(tenantTicketDTO.getCwId()));
        message = StrUtil.format(message, params);
        messages.setMessage(message);
        messages.setBusinessId(tenantTicketDTO.getCwId());
        insertMessage();
    }
}
